﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using MiniExcelLibs;
using System;

namespace CICDExam.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        [HttpGet]
        public async Task<IActionResult> ExportExcel()
        {


            ////开始手动线程
            //Thread th = new Thread(new ThreadStart(ExportExcelThread));
            //th.Start();
            //Thread th1 = new Thread(new ThreadStart(ExportExcelThread));
            //th1.Start();

            List<Person> persons = new List<Person>();
            var memory = new MemoryStream();
            //开始异步自动线程池
            await Task.Run(() =>
            {
                
                for (int i = 0; i < 1000000; i++)
                {
                    persons.Add(new Person() { Name = "Tom" + i, Age = 25 });
                    persons.Add(new Person() { Name = "Jerry" + i, Age = 30 });
                    persons.Add(new Person() { Name = "Mary" + i, Age = 28 });
                }
                
                memory.SaveAs(persons);
                memory.Seek(0, SeekOrigin.Begin);
                
            });
            return File(memory, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Persons.xlsx");
            //return Ok(1);
        }

        private void ExportExcelThread()
        {
            //// 线程锁
            //页面卡死，等待锁释放
            //lock 为什么必须只能锁引用类型?不能锁值类型？什么原因
            //
            lock (this)
            {

            }
            // Export Excel code here
        }
    }

    public record Person()
    {
         public string Name { get; set; }
         public int Age { get; set; }
    }
}
